// open -a Google\ Chrome --args --allow-file-access-from-files

define(['jquery', 'common/util/string'], function($, string) {

var fileUrl = {};

function parentPath(path) {
  return path.slice(0, path.lastIndexOf('/') + 1);
};

function currentDirectory() {
  return parentPath(window.location.href);
};

function expandDots(path) {
  if (string.beginsWith(path, '../')) {
    return parentPath(currentDirectory()) + path.slice(3);
  } else if (string.beginsWith(path, './')) {
    return currentDirectory() + path.slice(2);
  }
};

function traverseDirectoryHelper(path, context) {
  context.pendingRequestCount++;
  $.get(path + '?bust=' + Date.now(), function(data) {
    var rowRegex = /addRow\("[^"]*","([^"]*)",([01]),/g;

    while (true) {
      var result = rowRegex.exec(data);
      if (result == null) {
        break;
      }
      if (result[1] == '.' || result[1] == '..') {
        continue;
      }

      var filename = result[1];
      var isDirectory = (result[2] == '1');

      if (isDirectory) {
        traverseDirectoryHelper(path + filename + '/', context);
      } else {
        context.processFile(path + filename);
      }
    }

    context.pendingRequestCount--;
    if (0 == context.pendingRequestCount) {
      context.onComplete();
    }
  });
};

function traverseDirectory(rootPath, processFile, onComplete) {
  var context = {
    pendingRequestCount: 0,
    processFile: processFile,
    onComplete: onComplete
  };
  traverseDirectoryHelper(rootPath, context);
};

fileUrl.relativePath = function(parentPath, childPath) {
  var canonicalParentPath = expandDots(parentPath);
  var canonicalChildPath = expandDots(childPath);
  return canonicalChildPath.slice(canonicalParentPath.length);
};

fileUrl.isChild = function(parentPath, childPath) {
  var canonicalParentPath = expandDots(parentPath);
  var canonicalChildPath = expandDots(childPath);
  return string.beginsWith(canonicalChildPath, canonicalParentPath);
};

fileUrl.findFiles = function(path, includeFile, onComplete) {
  var files = [];

  function processFile(file) {
    if (includeFile(file)) {
      files.push(file);
    }
  }

  function onTraverseComplete() {
    onComplete(files);
  }

  traverseDirectory(path, processFile, onTraverseComplete);
};

return fileUrl;

});
